﻿namespace Oddo.Concept.Crm.Common.Behaviors
{
    using System;
    using System.Collections.Generic;
    using Microsoft.Practices.Unity.InterceptionExtension;
    using System.Diagnostics;
    using System.Threading.Tasks;

    public class MethodCallTraceBehavior : IInterceptionBehavior
    {
        private readonly TraceSource _trace = new TraceSource("MethodCallTraceBehavior");

        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            var st = new Stopwatch();
            st.Start();

            var methodReturn = getNext().Invoke(input, getNext);
            if (methodReturn.ReturnValue is Task)
            {
                var t = methodReturn.ReturnValue as Task;
                t.ContinueWith(task =>
                    {
                        st.Stop();
                        _trace.TraceEvent(TraceEventType.Verbose, 0, "The call to method {0}.{1}.{2} elapsed {3}", input.MethodBase.DeclaringType.Namespace, input.MethodBase.DeclaringType.Name, input.MethodBase.Name, st.Elapsed);
                    });
            }
            else
            {
                st.Stop();
                _trace.TraceEvent(TraceEventType.Verbose, 0, "The call to method {0}.{1}.{2} elapsed {3}", input.MethodBase.DeclaringType.Namespace, input.MethodBase.DeclaringType.Name, input.MethodBase.Name, st.Elapsed);
            }
            return methodReturn;
        }

        public IEnumerable<Type> GetRequiredInterfaces()
        {
            return Type.EmptyTypes;
        }

        public bool WillExecute { get { return true; } }
    }
}